package com.huangmingfu;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;

/**
 * @Author: 黄名富
 * @Description: RMI 本地
 */
public class RmiLocal {

    public static void main(String[] args) throws MalformedURLException, NotBoundException, RemoteException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        String serviceName = "rmi://localhost:" + 8080 + "/remoteService";
        reflectRemote(serviceName);
        interfaceRemote(serviceName);
    }

    // 这种方式仍然需要导入远程服务提供的接口，RemoteService
    private static void reflectRemote(String serviceName) throws MalformedURLException, NotBoundException, RemoteException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Remote lookup = Naming.lookup(serviceName);
        Method method = lookup.getClass().getMethod("service", String.class);
        Object result = method.invoke(lookup, "反射方式");
        System.out.println("反射方式，远程调用结果：" + result);
    }

    private static void interfaceRemote(String serviceName) throws MalformedURLException, NotBoundException, RemoteException{
        RemoteService remoteService = (RemoteService)Naming.lookup(serviceName);
        String result = remoteService.service("接口方式");
        System.out.println("接口方式，远程调用结果：" + result);
    }

}
